﻿Create PROCEDURE [dbo].[proc_Loan_HK_ByJE]
	(
		@id INT,	
		@hkje decimal(18,2)
	)
AS
BEGIN
	
BEGIN TRANSACTION--开始事务
DECLARE @errorSum INT --定义错误计数器
DECLARE @JKJE Decimal(18,2)
DECLARE @CurrentDate DateTime = GetDate()

SET @errorSum=0 --没错为0
	
	DECLARE @f INT
	SELECT @f=flag,@JKJE=[Money] FROM Loan l WHERE id=@id
	
	IF @f=1
	BEGIN
		RETURN
	END
	--还款大于借款
	IF @hkje>@JKJE
	Begin
		Return
	ENd
	--还款金额与借款相同
	IF @hkje=@JKJE
	Begin
		UPDATE Loan
		SET
			flag = 1,HKDate = @CurrentDate WHERE id=@id
	End	
	Else--还款金额小于借款，拆分借款
	Begin
		Insert Into Loan([Summary],[CompanyId],[CompanyName],[DepartmentId],[DepartmentName],[ENameId],[EName],[PostCategoryId],[PostCategory]
		   ,[Address],[Days],[Money],[Cause],[PZPerson],[PZPersonName],[SHPerson],[SHPersonName],[lrrq],[userid],[username],[flag]
		   ,[PaymentTypeId],[PaymentTypeName],[BankId],[BankName],[HKDate],[typeid])
		Select [Summary],[CompanyId],[CompanyName],[DepartmentId],[DepartmentName],[ENameId],[EName],[PostCategoryId],[PostCategory]
		   ,[Address],[Days],@JKJE-@hkje,[Cause],[PZPerson],[PZPersonName],[SHPerson],[SHPersonName],[lrrq],[userid],[username],[flag]
		   ,[PaymentTypeId],[PaymentTypeName],[BankId],[BankName],[HKDate],[typeid] from Loan where id=@id

		UPDATE Loan
		SET
			[Money]=@hkje,flag = 1,HKDate = @CurrentDate WHERE id=@id
	End

if @@ROWCOUNT<1
		begin
			set @errorSum+=1		
			goto e;
		end

INSERT INTO [Finance_RunningAccount]
           (
           [CreateDate]
           ,[TradeDate]
           ,[Summary]
           ,[AccountsTypeId]
           ,[AccountsTypeName]
           ,[ParentId]
           ,[ParentName]
           ,[SubjectId]
           ,[SubjectName]
           ,[PaymentTypeId]
           ,[PaymentTypeName]
           ,[BankId]
           ,[BankName]
           ,[Income]
           ,[Outlay]
           ,[Agent]
           ,[AgentName]
           ,[UserName]
           ,[EName]
           ,[CompanyId]
           ,[Description]
           ,[BillNumber]
           ,[OrderId]
           ,[Renling]
           ,[IOTypeId]
           ,[isGreen],l_id)
     SELECT 
           
           @CurrentDate
           ,CONVERT(VARCHAR(10),@CurrentDate,120)
           ,'[借款收入]'+l.Summary
           ,1
           ,'收入'
           ,0
           ,''
           ,0
           ,''
           ,[PaymentTypeId]
           ,[PaymentTypeName]
           ,[BankId]
           ,[BankName]
           ,@hkje
           ,0
           ,l.ENameId
           ,l.EName
           ,l.userid
           ,l.username
           ,l.CompanyId
           ,l.Cause
           ,''
           ,''
           ,2
           ,0
           ,0,@id
     FROM Loan l WHERE  l.id=@id
           
if @@ROWCOUNT<1
	begin
		set @errorSum+=1		
		goto e;
    end

e:
    PRINT @errorSum
	if @errorSum>0
	begin
		rollback TRANSACTION
	
	end
	else
	begin
		commit TRANSACTION
	END
end		
	RETURN
